#include <brpc/server.h>
#include <butil/logging.h>
#include <thread>

#include "data/mysql.hpp"
#include "data/mysql_message.hpp"
#include "data/es.hpp"

#include "channel.hpp"
#include "etcd.hpp"     // 服务注册模块封装
#include "logger.hpp"   // 日志模块封装
#include "rabbitmq.hpp" // 消息队列封装
#include "utils.hpp"

#include "base.pb.h"
#include "user.pb.h"
#include "file.pb.h"
#include "message.pb.h"  // protobuf框架代码


namespace im
{
class MsgStorageServiceImpl :public MsgStorageService {
public:
    MsgStorageServiceImpl(
            const std::shared_ptr<elasticlient::Client> &es_client,
            const std::shared_ptr<odb::core::database> &mysql_client,
            const ServiceManager::ptr &channel_manager,
            const std::string &file_service_name, const std::string &user_service_name) :
            _es_msg(std::make_shared<ESMessage>(es_client)),
            _mysql_msg(std::make_shared<MessageTable>(mysql_client)),
            _file_service_name(file_service_name), _user_service_name(user_service_name),
            _mm_channels(channel_manager){
            _es_msg->createIndex();
        }

    virtual void GetHistoryMsg(google::protobuf::RpcController* controller,
                    const ::im::GetHistoryMsgReq* request,
                    ::im::GetHistoryMsgRsp* response,
                    ::google::protobuf::Closure* done){
        LOG_INFO("收到来自 {} 的 获取历史范围聊天信息 请求！", request->request_id());
        brpc::ClosureGuard rpc_guard(done);
        auto err_response = [this, response](const std::string& rid, const std::string& err){
            response->set_request_id(rid);
            response->set_success(false);
            response->set_errmsg(err);
        };
        //1.提取关键要素:会话ID，起始时间，结束时间
        std::string rid = request->request_id();
        std::string csid = request->chat_session_id();
        auto start_time = boost::posix_time::from_time_t(request->start_time());
        auto over_time = boost::posix_time::from_time_t(request->over_time());
        // 调试：打印一下起始时间和结束时间
        LOG_DEBUG("起始时间：{}，结束时间：{}", boost::posix_time::to_simple_string(start_time), boost::posix_time::to_simple_string(over_time));
        //2.从数据库中进行消息查询
        std::vector<Message> msg_list = _mysql_msg->range(csid, start_time, over_time);
        if(msg_list.empty()){
            response->set_request_id(rid);
            response->set_success(true);
            return ;
        }
        std::unordered_set<std::string> file_id_lists;
        //3.统计所有文件类型消息的文件ID，并从文件子服务进行批量文件下载
        for(auto msg : msg_list){
            if(msg.message_type() != MessageType::STRING || !msg.file_id().empty()){
                file_id_lists.insert(msg.file_id());
            }
        }
        std::unordered_map<std::string, std::string> file_data_lists;
        bool ret = _GetFile(rid, file_id_lists, file_data_lists);
        if(ret == false){
            LOG_CRITICAL("{} 批量文件数据下载失败！", rid);
            return err_response(rid, "批量文件数据下载失败!");
        }
        //4.统计所有消息的发送者用户ID，从用户子服务进行批量用户信息获取
        std::unordered_set<std::string> user_id_lists;
        for (const auto &msg : msg_list) {
            user_id_lists.insert(msg.user_id());
        }
        std::unordered_map<std::string, UserInfo> user_lists;
        ret = _GetUser(rid, user_id_lists, user_lists);
        if(ret == false){
            LOG_CRITICAL("{} 批量用户数据下载失败！", rid);
            return err_response(rid, "批量用户数据下载失败!");
        }
        //5.组织响应
        response->set_request_id(rid);
        response->set_success(true);
        for(const auto& msg : msg_list){
            auto message_info = response->add_msg_list();
            message_info->set_message_id(msg.message_id());
            message_info->set_chat_session_id(msg.session_id());
            message_info->set_timestamp(boost::posix_time::to_time_t(msg.create_time()));
            message_info->mutable_sender()->CopyFrom(user_lists[msg.user_id()]);
            switch(msg.message_type()) {
                case MessageType::STRING:
                    message_info->mutable_message()->set_message_type(MessageType::STRING);
                    message_info->mutable_message()->mutable_string_message()->set_content(msg.content());
                    break;
                case MessageType::IMAGE:
                    message_info->mutable_message()->set_message_type(MessageType::IMAGE);
                    message_info->mutable_message()->mutable_image_message()->set_file_id(msg.file_id());
                    message_info->mutable_message()->mutable_image_message()->set_image_content(file_data_lists[msg.file_id()]);
                    break;
                case MessageType::FILE:
                    message_info->mutable_message()->set_message_type(MessageType::FILE);
                    message_info->mutable_message()->mutable_file_message()->set_file_id(msg.file_id());
                    message_info->mutable_message()->mutable_file_message()->set_file_size(msg.file_size());
                    message_info->mutable_message()->mutable_file_message()->set_file_name(msg.file_name());
                    message_info->mutable_message()->mutable_file_message()->set_file_contents(file_data_lists[msg.file_id()]);
                    break;
                case MessageType::SPEECH:
                    message_info->mutable_message()->set_message_type(MessageType::SPEECH);
                    message_info->mutable_message()->mutable_speech_message()->set_file_id(msg.file_id());
                    message_info->mutable_message()->mutable_speech_message()->set_file_contents(file_data_lists[msg.file_id()]);
                    break;
                default:
                    LOG_CRITICAL("消息类型错误！！");
                    return;
            }
        }
    }
    virtual void GetRecentMsg(google::protobuf::RpcController* controller,
                        const ::im::GetRecentMsgReq* request,
                        ::im::GetRecentMsgRsp* response,
                        ::google::protobuf::Closure* done){
        LOG_INFO("收到来自 {} 的 获取最近N条聊天信息 请求！", request->request_id());
        brpc::ClosureGuard rpc_guard(done);
        auto err_response = [this, response](const std::string& rid, const std::string& err){
            response->set_request_id(rid);
            response->set_success(false);
            response->set_errmsg(err);
        };

        //1.提取关键要素:会话ID，起始时间，结束时间
        std::string rid = request->request_id();
        std::string csid = request->chat_session_id();
        int limit = request->msg_count();
        //2.从数据库中进行消息查询
        std::vector<Message> msg_list = _mysql_msg->recent(csid, limit);
        if(msg_list.empty()){
            response->set_request_id(rid);
            response->set_success(true);
            return ;
        }
        std::unordered_set<std::string> file_id_lists;
        //3.统计所有文件类型消息的文件ID，并从文件子服务进行批量文件下载
        for(auto msg : msg_list){
            if(msg.message_type() != MessageType::STRING || !msg.file_id().empty()){
                file_id_lists.insert(msg.file_id());
            }
        }
        std::unordered_map<std::string, std::string> file_data_lists;
        bool ret = _GetFile(rid, file_id_lists, file_data_lists);
        if(ret == false){
            LOG_CRITICAL("{} 批量文件数据下载失败！", rid);
            return err_response(rid, "批量文件数据下载失败!");
        }
        //4.统计所有消息的发送者用户ID，从用户子服务进行批量用户信息获取
        std::unordered_set<std::string> user_id_lists;
        for (const auto &msg : msg_list) {
            user_id_lists.insert(msg.user_id());
        }
        std::unordered_map<std::string, UserInfo> user_lists;
        ret = _GetUser(rid, user_id_lists, user_lists);
        if(ret == false){
            LOG_CRITICAL("{} 批量用户数据下载失败！", rid);
            return err_response(rid, "批量用户数据下载失败!");
        }
        //5.组织响应
        response->set_request_id(rid);
        response->set_success(true);
        for(const auto& msg : msg_list){
            auto message_info = response->add_msg_list();
            message_info->set_message_id(msg.message_id());
            message_info->set_chat_session_id(msg.session_id());
            message_info->set_timestamp(boost::posix_time::to_time_t(msg.create_time()));
            message_info->mutable_sender()->CopyFrom(user_lists[msg.user_id()]);
            switch(msg.message_type()) {
                case MessageType::STRING:
                    message_info->mutable_message()->set_message_type(MessageType::STRING);
                    message_info->mutable_message()->mutable_string_message()->set_content(msg.content());
                    break;
                case MessageType::IMAGE:
                    message_info->mutable_message()->set_message_type(MessageType::IMAGE);
                    message_info->mutable_message()->mutable_image_message()->set_file_id(msg.file_id());
                    message_info->mutable_message()->mutable_image_message()->set_image_content(file_data_lists[msg.file_id()]);
                    break;
                case MessageType::FILE:
                    message_info->mutable_message()->set_message_type(MessageType::FILE);
                    message_info->mutable_message()->mutable_file_message()->set_file_id(msg.file_id());
                    message_info->mutable_message()->mutable_file_message()->set_file_size(msg.file_size());
                    message_info->mutable_message()->mutable_file_message()->set_file_name(msg.file_name());
                    message_info->mutable_message()->mutable_file_message()->set_file_contents(file_data_lists[msg.file_id()]);
                    break;
                case MessageType::SPEECH:
                    message_info->mutable_message()->set_message_type(MessageType::SPEECH);
                    message_info->mutable_message()->mutable_speech_message()->set_file_id(msg.file_id());
                    message_info->mutable_message()->mutable_speech_message()->set_file_contents(file_data_lists[msg.file_id()]);
                    break;
                default:
                    LOG_CRITICAL("消息类型错误！！");
                    return;
            }
        }
    }
    virtual void MsgSearch(google::protobuf::RpcController* controller,
                        const ::im::MsgSearchReq* request,
                        ::im::MsgSearchRsp* response,
                        ::google::protobuf::Closure* done){
        LOG_INFO("收到来自 {} 的 搜索聊天消息 请求！", request->request_id());
        brpc::ClosureGuard rpc_guard(done);
        auto err_response = [this, response](const std::string& rid, const std::string& err){
            response->set_request_id(rid);
            response->set_success(false);
            response->set_errmsg(err);
        };
        //1.提取关键要素:会话ID，起始时间，结束时间
        std::string rid = request->request_id();
        std::string csid = request->chat_session_id();
        std::string skey = request->search_key();
        //2.从ES中进行消息查询
        std::vector<Message> msg_list = _es_msg->search(csid, skey);
        if(msg_list.empty()){
            response->set_request_id(rid);
            response->set_success(true);
            return ;
        }
        //3.统计所有消息的发送者用户ID，从用户子服务进行批量用户信息获取
        std::unordered_set<std::string> user_id_lists;
        for (const auto &msg : msg_list) {
            user_id_lists.insert(msg.user_id());
        }
        std::unordered_map<std::string, UserInfo> user_lists;
        bool ret = _GetUser(rid, user_id_lists, user_lists);
        if(ret == false){
            LOG_CRITICAL("{} 批量用户数据下载失败！", rid);
            return err_response(rid, "批量用户数据下载失败!");
        }
        //4.组织响应
        response->set_request_id(rid);
        response->set_success(true);
        for(const auto& msg : msg_list){
            auto message_info = response->add_msg_list();
            message_info->set_message_id(msg.message_id());
            message_info->set_chat_session_id(msg.session_id());
            message_info->set_timestamp(boost::posix_time::to_time_t(msg.create_time()));
            message_info->mutable_sender()->CopyFrom(user_lists[msg.user_id()]);
            message_info->mutable_message()->set_message_type(MessageType::STRING);
            message_info->mutable_message()->mutable_string_message()->set_content(msg.content());
        }
    }

    // 消息处理的回调函数
    void onMessage(const char *body, size_t size){
        LOG_DEBUG("收到新消息，进行存储处理！");
        //1. 取出序列化的消息内容，进行反序列化
        MessageInfo msg_info;
        if(false == msg_info.ParseFromArray(body, size)){
            LOG_CRITICAL("对消费到的消息进行反序列化失败！");
            return;
        }
        //2. 根据不同的消息类型进行不同的处理
        auto msg_type = msg_info.message().message_type();
        std::string file_id, filename, content;
        int64_t file_size = 0;
        switch(msg_type){
            //  1. 文本类型消息，取元信息存储到ES中
            case MessageType::STRING:{
                LOG_DEBUG("收到文本消息！");
                content = msg_info.message().string_message().content();
                file_size = content.size();
                bool ret = _es_msg->appendData(msg_info.sender().user_id(),
                                    msg_info.message_id(),
                                    msg_info.chat_session_id(),
                                    content,
                                    msg_info.timestamp());
                if (ret == false) {
                    LOG_CRITICAL("文本消息向存储引擎进行存储失败！");
                    return;
                }
                break;
            }
            //  2. 其他类型消息，通过调用文件子服务进行服务器存储，并返回文件id
            case MessageType::IMAGE:{
                auto& msg = msg_info.message().image_message().image_content();
                file_size = msg.size();
                bool ret = _PutFile("", msg, file_size, file_id);
                if (ret == false) {
                    LOG_CRITICAL("上传图片到文件子服务失败！");
                    return ;
                }
                break;
            }
            case MessageType::FILE:{
                filename = msg_info.message().file_message().file_name();
                auto& msg = msg_info.message().file_message().file_contents();
                file_size = msg_info.message().file_message().file_size();
                bool ret = _PutFile(filename, msg, file_size, file_id);
                if (ret == false) {
                    LOG_CRITICAL("上传文件到文件子服务失败！");
                    return ;
                }
                break;
            }
            case MessageType::SPEECH:{
                auto& msg = msg_info.message().speech_message().file_contents();
                file_size = msg.size();
                bool ret = _PutFile("", msg, file_size, file_id);
                if (ret == false) {
                    LOG_CRITICAL("上传语言到文件子服务失败！");
                    return ;
                }
                break;
            }
        }
        //3. 提取消息的元信息，存储到mysql数据库中
        Message msg;
        msg.user_id(msg_info.sender().user_id());
        msg.message_id(msg_info.message_id());
        msg.session_id(msg_info.chat_session_id());
        msg.message_type(msg_type);
        msg.create_time(boost::posix_time::from_time_t(msg_info.timestamp()));
        msg.content(content);

        msg.file_name(filename);
        msg.file_id(file_id);
        msg.file_size(file_size);
        bool ret = _mysql_msg->insert(msg);
        if (ret == false) {
            LOG_CRITICAL("向数据库插入新消息失败！");
            return;
        }
    }

private:
    bool _PutFile(const std::string &filename, const std::string &body, 
                const int64_t fsize, std::string &file_id){
        auto channel = _mm_channels->choose(_file_service_name);
        if(channel == nullptr){
            LOG_CRITICAL("{} 没有可供访问的文件子服务节点！",  _file_service_name);
            return false;
        }
        FileService_Stub stub(channel.get());
        PutSingleFileReq req;
        req.set_request_id(uuid());
        req.mutable_file_data()->set_file_name(filename);
        req.mutable_file_data()->set_file_size(fsize);
        req.mutable_file_data()->set_file_content(body);
        PutSingleFileRsp rsp;
        brpc::Controller cntl;
        stub.PutSingleFile(&cntl, &req, &rsp, nullptr);
        if(cntl.Failed() || rsp.success() == false){
            LOG_CRITICAL("文件子服务节点{}调用失败！-- {}", _file_service_name, cntl.ErrorText());
            return false;
        }
        file_id = rsp.file_info().file_id();
        return true;
    }

    bool _GetFile(const std::string &rid, std::unordered_set<std::string>& file_id_lists,
                std::unordered_map<std::string, std::string>& file_data_lists){
        auto channel = _mm_channels->choose(_file_service_name);
        if(channel == nullptr){
            LOG_CRITICAL("{} 没有可供访问的文件子服务节点！",  _file_service_name);
            return false;
        }
        FileService_Stub stub(channel.get());
        GetMultiFileReq req;
        req.set_request_id(rid);
        for (const auto &id : file_id_lists) {
            req.add_file_id_list(id);
        }
        GetMultiFileRsp rsp;
        brpc::Controller cntl;
        stub.GetMultiFile(&cntl, &req, &rsp, nullptr);
        if(cntl.Failed() || rsp.success() == false){
            LOG_CRITICAL("文件子服务节点{}调用失败！-- {}", _file_service_name, cntl.ErrorText());
            return false;
        }
        for(const auto &file_data : rsp.file_data()){
            file_data_lists.insert(std::make_pair(file_data.first, file_data.second.file_content()));
        }
        return true;
    }

    bool _GetUser(const std::string &rid, std::unordered_set<std::string>& user_id_lists,
                std::unordered_map<std::string, UserInfo>& user_data_lists){
        auto channel = _mm_channels->choose(_user_service_name);
        if(channel == nullptr){
            LOG_CRITICAL("{} 没有可供访问的用户子服务节点！",  _user_service_name);
            return false;
        }
        UserService_Stub stub(channel.get());
        GetMultiUserInfoReq req;
        req.set_request_id(rid);
        for (const auto &id : user_id_lists) {
            req.add_users_id(id);
        }
        GetMultiUserInfoRsp rsp;
        brpc::Controller cntl;
        stub.GetMultiUserInfo(&cntl, &req, &rsp, nullptr);
        if(cntl.Failed() || rsp.success() == false){
            LOG_CRITICAL("用户子服务节点{}调用失败！-- {}", _user_service_name, cntl.ErrorText());
            return false;
        }
        for(const auto &user : rsp.users_info()){
            user_data_lists.insert(std::make_pair(user.first, user.second));
        }
        return true;
    }

private:
    ESMessage::ptr _es_msg;
    MessageTable::ptr _mysql_msg;

    std::string _user_service_name;
    std::string _file_service_name;
    ServiceManager::ptr _mm_channels;
};

class MsgStorageServer{

public:
    using ptr = std::shared_ptr<MsgStorageServer>;
    MsgStorageServer(const MQClient::ptr &mq_client,
            const Discover::ptr service_discoverer, 
            const Registry::ptr &reg_client,
            const std::shared_ptr<elasticlient::Client> &es_client,
            const std::shared_ptr<odb::core::database> &mysql_client,
            const std::shared_ptr<brpc::Server> &server):
            _service_discoverer(service_discoverer),
            _registry_client(reg_client),
            _es_client(es_client),
            _mysql_client(mysql_client),
            _mq_client(mq_client),
            _rpc_server(server){}

    void start(){
        _rpc_server->RunUntilAskedToQuit();
    }
    

private:
    Discover::ptr _service_discoverer;
    Registry::ptr _registry_client;

    std::shared_ptr<odb::core::database> _mysql_client;
    std::shared_ptr<elasticlient::Client> _es_client;
    MQClient::ptr _mq_client;

    std::shared_ptr<brpc::Server> _rpc_server;
};

class MsgStoreServerBuild{
public:
    MsgStoreServerBuild(){}

    void init_ES_client(const std::vector<std::string> host_list){
        _es_client = ESClientFactory::create(host_list);
    }

    void init_MySql_client(
            const std::string &user, const std::string &pwd,
            const std::string &host, const std::string &db,
            const std::string &cset, int port, int conn_pool_count){
        _mysql_client = ODBFactory::create(user, pwd, host, db, cset, port, conn_pool_count);
    }

    void init_MQ_client(const std::string &user, 
        const std::string &passwd,
        const std::string &host,
        const std::string &exchange_name,
        const std::string &queue_name,
        const std::string &binding_key){
        _mq_client = std::make_shared<MQClient>(user, passwd, host);
        _mq_client->declare_component(exchange_name, queue_name, binding_key);
        _exchange_name = exchange_name;
        _queue_name = queue_name;
    }

    void init_discovery_client(const std::string &reg_host,
            const std::string &base_service_name,
            const std::string &file_service_name,
            const std::string &user_service_name){
        _user_service_name = user_service_name;
        _file_service_name = file_service_name;
        _mm_channels = std::make_shared<ServiceManager>();
        _mm_channels->declared(file_service_name);
        _mm_channels->declared(user_service_name);
        auto put_cb = std::bind(&ServiceManager::onServiceOnline, _mm_channels.get(), std::placeholders::_1, std::placeholders::_2);
        auto del_cb = std::bind(&ServiceManager::onServiceOffline, _mm_channels.get(), std::placeholders::_1, std::placeholders::_2);
        _discover_client = std::make_shared<Discover>(reg_host, base_service_name, put_cb, del_cb);
    }

    void init_register_client(const std::string& reg_host, const std::string& service_name, const std::string& access_host){
        _registry_client = std::make_shared<Registry>(reg_host);
        _registry_client->register_server(service_name, access_host);
    }

    void init_rpc_server(uint port, int timeout, int num_threads){
        if (!_es_client) {
            LOG_CRITICAL("还未初始化“ES搜索”模块！");
            abort();
        }
        if (!_mysql_client) {
            LOG_CRITICAL("还未初始化“mysql客户端”模块! ");
            abort();
        }
        if (!_mq_client) {
            LOG_CRITICAL("还未初始化“MQ消息队列”模块！");
            abort();
        }
        if (!_mm_channels) {
            LOG_CRITICAL("还未初始化“信道管理”模块！");
            abort();
        }
        _rpc_server = std::make_shared<brpc::Server>();
        auto* msg_service = new MsgStorageServiceImpl(_es_client, _mysql_client, _mm_channels, 
                                                _file_service_name, _user_service_name);
        int ret = _rpc_server->AddService(msg_service, brpc::ServiceOwnership::SERVER_OWNS_SERVICE);
        if (ret == -1) {
            LOG_CRITICAL("添加Rpc服务失败！");
            abort();
        }
        brpc::ServerOptions options;
        options.idle_timeout_sec = timeout;
        options.num_threads = num_threads;
        ret = _rpc_server->Start(port, &options);
        if (ret == -1) {
            LOG_CRITICAL("服务启动失败！");
            abort();
        }

        auto callback = std::bind(&MsgStorageServiceImpl::onMessage, msg_service, 
                                std::placeholders::_1, std::placeholders::_2);
        _mq_client->consume(_queue_name, callback);
    }

    MsgStorageServer::ptr Build(){
        if (!_discover_client) {
            LOG_CRITICAL("还未初始化“服务发现”模块! ");
            abort();
        }
        if (!_registry_client) {
            LOG_CRITICAL("还未初始化“服务注册”模块！");
            abort();
        }
        if (!_rpc_server) {
            LOG_CRITICAL("还未初始化“RPC服务器”模块! ");
            abort();
        }

        return std::make_shared<MsgStorageServer>(
                _mq_client, _discover_client, _registry_client,
                _es_client, _mysql_client, _rpc_server);
    }

private:
    ServiceManager::ptr _mm_channels;
    std::string _user_service_name;
    std::string _file_service_name;
    Discover::ptr _discover_client;
    Registry::ptr _registry_client;

    std::shared_ptr<odb::core::database> _mysql_client;
    std::shared_ptr<elasticlient::Client> _es_client;

    std::string _exchange_name;
    std::string _queue_name;
    MQClient::ptr _mq_client;
    std::shared_ptr<brpc::Server> _rpc_server;
};

} // namespace im

